<?php
/**
 * Created by PhpStorm.
 * User: Season
 * Date: 2018/10/23
 * Time: 16:43
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\User as UserModel;
use app\api\model\UserAddress;
use app\api\service\Token as TokenService;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserExcption;

class Address extends BaseController
{
    protected  $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'createOrUpdateAddress,getUserAddress']
    ];

    public function getUserAddress(){
        $uid = TokenService::getCurrentUID ();
        $userAddress = UserAddress::where('user_id','=', $uid)->find ();
        if(!$userAddress){
            throw new UserExcption(
                [
                    'msg'=>'用户地址不存在',
                    'errorCode'=>60001
                ]);
        }
        return $userAddress;
    }

    public function createOrUpdateAddress(){
        $validate = new AddressNew();
        $validate->goCheck ();
        //根据令牌获取uid
        //根据uid查找用户数据如果不存在抛出异常
        $uid = TokenService::getCurrentUID ();
        $user = UserModel::get ($uid);
        if(!$user){
            throw new UserExcption();
        }
        $dataArray = $validate->getDataByRule(input ('post.'));
        $userAddress = $user->address;
        if(!$userAddress){
            $user->address ()->save ($dataArray);
        }
        else{
            $user->address->save($dataArray);
        }
        return json(new SuccessMessage(),201);
    }
}